package com.game.service.imp;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.game.mapper.UserMapper;
import com.game.modal.User;
import com.game.rpc.IWeixinService;
import com.game.service.IUserService;
import com.game.util.RedisClient;
import com.game.util.ResultInfo;

@Service
public class UserService implements IUserService {
	
	private static final Logger log = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private IWeixinService weixinService;
	@Autowired
	private RedisClient redisClient;
	@Override
	public ResultInfo login(User user) throws IOException {
		
		Map<String, String> sessionData;
		ResultInfo result = ResultInfo.ERROR;
		sessionData = weixinService.code2session(user.getJscode());
		String openid = sessionData.get("openid");
		if(!StringUtils.isEmpty(openid)){
		  result.setResult(sessionData);
		  user.setOpenid(openid);
		  User selectUser = userMapper.selectByPrimary(openid);
		  if(selectUser==null){
			  result = userMapper.insert(user)>0?ResultInfo.SUCCESS:ResultInfo.ERROR;
		  }else{
			  result = userMapper.update(user)>0?ResultInfo.SUCCESS:ResultInfo.ERROR;
		  }
		  Map<String,String> logindata = new HashMap<String,String>();
		  logindata.put("uid", openid);
		  logindata.put("pwd", openid);
		  result.setResult(logindata);
		  redisClient.set(openid,openid);
		}
		return result;
	}
	@Override
	public List<User> queryByRoomNo(String roomNo) {
		
		return userMapper.list(roomNo);
	}
	

}
